import Vue from "vue";
import VueRouter from "vue-router";
import DefaultTitle from "../utils/common";
import { GetMenu } from "../api/menu";

Vue.use(VueRouter);

const routes = [
  {
    path: "/Login",
    name: "Login",
    component: () => import("../views/Login"),
  },  
  {
    path: "/",
    name: "home",
    redirect: "/welcome",
    component: () => import("../views/Home.vue"),
    children: [
      {
        path: "/welcome",
        name: "welcome",
        component: () => import("../views/Welcome"),
      },
      {
        path: "/404",
        name: "notfound",
        component: () => import("../notfound"),
      },
    ],
  },
];

// 获取原型对象push函数
const originalPush = VueRouter.prototype.push;

// 获取原型对象replace函数
const originalReplace = VueRouter.prototype.replace;

// 修改原型对象中的push函数
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

// 修改原型对象中的replace函数
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch((err) => err);
};

const createRouter = () =>
  new VueRouter({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: routes,
  });

const router = createRouter();
            
/**
 * @description: 命名导出
 * @return {*}
 */
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}

/**
 *   From:/admin/list    To:/admin/add
 */
router.beforeEach(async (to, from, next) => {

  document.title = `${DefaultTitle}-${to.meta.title}`;

  //debugger;
  if (to.path == "/VuexComponent") {
    next();
  } else {
    if (Vue.ls.get("jwt") == undefined && to.path != "/login") {
      next("/login");
    } else {
      if (to.name == undefined) {
        debugger
        try {
          let { data } = await GetMenu();

          data
            .filter((m) => m.menuType == 2)
            .forEach((m) => {
              router.addRoute("home", {
                path: m.menuRoute,
                name: m.routeName,
                component: (resolve) =>
                  require(["../views/" + m.component], resolve),
                //component: () => import('../views/' + b),
                meta: {
                  title: m.menuName,
                },
              });
            });
        } catch (error) {
          Vue.ls.remove("jwt");
          next("/login");
        }

        router.addRoute("home", {
          path: "*",
          redirect: "/404",
          hidden: true,
        });
        debugger

        next({ ...to, replace: true });
      } else {
        debugger;
        next();
      }
    }
  }
});




router.afterEach((to, from) => {});

export default router;
